<template>
  <div class="orders-management">
    <!-- 筛选栏 -->
    <div class="filter-bar">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="订单状态">
          <el-select v-model="filterForm.status" placeholder="全部状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="待确认" value="pending" />
            <el-option label="制作中" value="preparing" />
            <el-option label="配送中" value="delivering" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="订单类型">
          <el-select v-model="filterForm.type" placeholder="全部类型" clearable>
            <el-option label="全部" value="" />
            <el-option label="外卖" value="delivery" />
            <el-option label="堂食" value="dine-in" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="searchOrders">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单列表 -->
    <div class="orders-list">
      <el-table :data="filteredOrders" style="width: 100%" v-loading="loading">
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="customerName" label="客户" width="120" />
        <el-table-column prop="customerPhone" label="联系电话" width="130" />
        <el-table-column label="订单详情" min-width="200">
          <template #default="{ row }">
            <div class="order-items">
              <div v-for="item in row.items" :key="item.id" class="order-item">
                {{ item.name }} x{{ item.quantity }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总金额" width="100">
          <template #default="{ row }">
            <span class="amount">¥{{ row.totalAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="80">
          <template #default="{ row }">
            <el-tag :type="row.type === 'delivery' ? 'warning' : 'info'">
              {{ row.type === 'delivery' ? '外卖' : '堂食' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'pending'"
              type="success"
              size="small"
              @click="confirmOrder(row)"
            >
              确认
            </el-button>
            <el-button
              v-if="row.status === 'preparing'"
              type="primary"
              size="small"
              @click="completeOrder(row)"
            >
              完成
            </el-button>
            <el-button
              v-if="['pending', 'preparing'].includes(row.status)"
              type="danger"
              size="small"
              @click="cancelOrder(row)"
            >
              取消
            </el-button>
            <el-button size="small" @click="viewOrderDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="订单详情" width="600px">
      <div v-if="selectedOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ selectedOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ selectedOrder.customerName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedOrder.customerPhone }}</el-descriptions-item>
          <el-descriptions-item label="订单类型">
            {{ selectedOrder.type === 'delivery' ? '外卖' : '堂食' }}
          </el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(selectedOrder.status)">
              {{ getStatusText(selectedOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ selectedOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item v-if="selectedOrder.address" label="配送地址" :span="2">
            {{ selectedOrder.address }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedOrder.remark" label="备注" :span="2">
            {{ selectedOrder.remark }}
          </el-descriptions-item>
        </el-descriptions>
        
        <h4 style="margin: 20px 0 10px 0;">订单商品</h4>
        <el-table :data="selectedOrder.items" style="width: 100%">
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="price" label="单价" width="80">
            <template #default="{ row }">¥{{ row.price }}</template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="60" />
          <el-table-column label="小计" width="80">
            <template #default="{ row }">¥{{ (row.price * row.quantity).toFixed(2) }}</template>
          </el-table-column>
        </el-table>
        
        <div class="order-summary">
          <div class="summary-item">
            <span>商品总计：</span>
            <span>¥{{ selectedOrder.itemsAmount }}</span>
          </div>
          <div v-if="selectedOrder.deliveryFee" class="summary-item">
            <span>配送费：</span>
            <span>¥{{ selectedOrder.deliveryFee }}</span>
          </div>
          <div class="summary-item total">
            <span>订单总计：</span>
            <span>¥{{ selectedOrder.totalAmount }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderAPI } from '@/api'
import axios from 'axios'

const loading = ref(false)
const showDetailDialog = ref(false)
const selectedOrder = ref(null)

const filterForm = reactive({
  status: '',
  type: '',
  dateRange: []
})

// 订单数据
const orders = ref([])

const filteredOrders = computed(() => {
  return orders.value.filter(order => {
    if (filterForm.status && order.status !== filterForm.status) return false
    if (filterForm.type && order.type !== filterForm.type) return false
    // 这里可以添加日期范围过滤逻辑
    return true
  })
})

const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'preparing': 'primary',
    'delivering': 'info',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'pending': '待确认',
    'preparing': '制作中',
    'delivering': '配送中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true
    const response = await orderAPI.getOrders()
    
    if (response && response.success) {
      orders.value = response.data.map(order => ({
        id: order.id,
        orderNo: order.orderNumber,
        customerName: order.customerName || '匿名用户',
        customerPhone: order.customerPhone || '',
        items: order.items || [],
        itemsAmount: order.itemsAmount || 0,
        deliveryFee: order.deliveryFee || 0,
        totalAmount: order.totalAmount,
        type: order.orderType === 'DELIVERY' ? 'delivery' : 'dine-in',
        status: getOrderStatus(order.status),
        address: order.deliveryAddress || '',
        remark: order.remark || '',
        createTime: order.createdAt
      }))
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 订单状态映射
const getOrderStatus = (status) => {
  const statusMap = {
    'PENDING_PAYMENT': 'pending',
    'PAID': 'pending',
    'PROCESSING': 'preparing',
    'DELIVERING': 'delivering',
    'COMPLETED': 'completed',
    'CANCELLED': 'cancelled'
  }
  return statusMap[status] || 'pending'
}

const confirmOrder = async (order) => {
  try {
    await ElMessageBox.confirm('确认接受这个订单吗？', '确认订单', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    // 调用API更新订单状态
    const response = await orderAPI.updateOrder(order.id, { status: 'PROCESSING' })
    if (response && response.success) {
      order.status = 'preparing'
      ElMessage.success('订单已确认，开始制作')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认订单失败:', error)
      ElMessage.error('确认订单失败')
    }
  }
}

const completeOrder = async (order) => {
  try {
    const newStatus = order.type === 'delivery' ? 'DELIVERING' : 'COMPLETED'
    const response = await orderAPI.updateOrder(order.id, { status: newStatus })
    
    if (response && response.success) {
      order.status = order.type === 'delivery' ? 'delivering' : 'completed'
      ElMessage.success(order.type === 'delivery' ? '订单已完成，开始配送' : '订单已完成')
    }
  } catch (error) {
    console.error('完成订单失败:', error)
    ElMessage.error('完成订单失败')
  }
}

const cancelOrder = async (order) => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '取消订单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await orderAPI.updateOrder(order.id, { status: 'CANCELLED' })
    if (response && response.success) {
      order.status = 'cancelled'
      ElMessage.success('订单已取消')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

const viewOrderDetail = (order) => {
  selectedOrder.value = order
  showDetailDialog.value = true
}

const searchOrders = () => {
  // 重新获取订单数据，应用过滤条件
  fetchOrders()
}

const resetFilter = () => {
  Object.assign(filterForm, {
    status: '',
    type: '',
    dateRange: []
  })
  // 重置后重新获取数据
  fetchOrders()
}

onMounted(() => {
    // 初始化加载订单数据
    fetchOrders()
  })

onMounted(() => {
  console.log('Orders management mounted')
})
</script>

<style lang="scss" scoped>
.orders-management {
  .filter-bar {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .orders-list {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .order-items {
      .order-item {
        font-size: 14px;
        color: #606266;
        margin-bottom: 4px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
    
    .amount {
      font-weight: 600;
      color: #f56c6c;
    }
  }
  
  .order-detail {
    .order-summary {
      margin-top: 20px;
      padding: 16px;
      background: #f8f9fa;
      border-radius: 6px;
      
      .summary-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        &.total {
          font-weight: 600;
          font-size: 16px;
          color: #f56c6c;
          border-top: 1px solid #e4e7ed;
          padding-top: 8px;
          margin-top: 8px;
        }
      }
    }
  }
}
</style>